package com.example.test.service;

import com.example.test.dao.UserMapper;
import com.example.test.pojo.User;
import com.example.test.vo.ResponseVo;
import com.example.test.vo.UserVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    UserMapper userMapper;

    @Override
    public UserVo getUserInfo(Integer userId) {
        User user = userMapper.selectByPrimaryKey(userId);
        UserVo userVo = new UserVo();
        // 第一个参数是被复制的对象,将user对象的属性值复制到userVo中
        BeanUtils.copyProperties(user, userVo);
        return userVo;
    }


    /*
    * 获取用户信息
    * */
    @Override
    public List<UserVo> getUserList() {
        List<User> allUser = userMapper.getAllUser();

        List<UserVo> res = new ArrayList<>();
        for (int i = 0; i < allUser.size(); i++) {
            UserVo userVo = new UserVo();
            BeanUtils.copyProperties(allUser.get(i), userVo);
            res.add(userVo);
        }
        return res;
    }

    @Override
    public ResponseVo<PageInfo<UserVo>> list(String username, Integer pageNum, Integer pageSize) {
        System.out.println(username + " " + pageNum + " " + pageSize);
        PageHelper.startPage(pageNum, pageSize);
        List<User> list = userMapper.list(username);

        List<UserVo> userVos = list.stream().map(e->{
            UserVo userVo = new UserVo();
            BeanUtils.copyProperties(e, userVo);
            return userVo;
        }).collect(Collectors.toList());

        PageInfo pageInfo = new PageInfo<>(userVos);
        return ResponseVo.success(pageInfo);
    }
}
